package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.dtos.ArticleCommentDto;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;

import com.heima.model.article.dtos.ArticleInfoDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.vos.ArticleCommnetVo;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.comment.dtos.CommentConfigDto;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.ArticleVisitStreamMess;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.wemedia.dtos.StatisticsDto;
import com.heima.utils.common.DateUtils;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

import static com.heima.common.constants.ArticleConstants.*;


@Service
@Transactional
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {
    @Autowired
    private ApArticleMapper articleMapper;
    // 单页最大加载的数字
    private final static short MAX_PAGE_SIZE = 50;

    /**
     * 加载文章列表
     *
     * @param type 1为加载更多  2为加载最新
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(Short type, ArticleHomeDto dto) {
        //1.校验参数
        //分页条数校验
        Integer size = dto.getSize();
        if (size == null | size == 0) {
            size = 10;
        }
        //分页值不超过50
        size = Math.min(size, MAX_PAGE_SIZE);
        //type参数校验
        if (!type.equals(LOADTYPE_LOAD_MORE) && !type.equals(LOADTYPE_LOAD_NEW)) {
            type = LOADTYPE_LOAD_MORE;
        }
        //频道参数校验
        if (StringUtils.isBlank(dto.getTag())) {
            dto.setTag(DEFAULT_TAG);
        }
        //时间参数校验
        if (dto.getMaxBehotTime() == null) {
            dto.setMaxBehotTime(new Date());
        }
        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }
        //2.查询
        List<ApArticle> articleList = articleMapper.loadArticleList(dto, type);
        //3.返回结果
        return ResponseResult.okResult(articleList);
    }

    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;
    @Autowired
    private ApArticleContentMapper apArticleContentMapper;
    @Autowired
    private ArticleFreemarkerService articleFreemarkerService;

    /**
     * 保存app相关文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveArticle(ArticleDto dto) {
        //1.检查参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto, apArticle);
        //2.判断id是否存在
        if (dto.getId() == null) {
            //2.1不存在ID  保存： 文章 文章配置 文章内容
            ApUser user = AppThreadLocalUtil.getUser();
            apArticle.setAuthorId(user.getId().longValue());
            save(apArticle);  //保存文章
            //保存文章配置
            ApArticleConfig apArticleConfig = new ApArticleConfig(apArticle.getId());
            apArticleConfigMapper.insert(apArticleConfig);
            //保存文章内容
            ApArticleContent articleContent = new ApArticleContent();
            String content = dto.getContent();
            articleContent.setContent(content);
            articleContent.setArticleId(apArticle.getId());
            apArticleContentMapper.insert(articleContent);
        } else {
            //2.2存在id  修改： 文章  文章内容
            updateById(apArticle);
            //修改文章内容
            LambdaQueryWrapper<ApArticleContent> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ApArticleContent::getArticleId, dto.getId());
            ApArticleContent articleContent = apArticleContentMapper.selectOne(wrapper);
            articleContent.setContent(dto.getContent());
            apArticleContentMapper.updateById(articleContent);

        }
        //异步调用      生成静态文件上传minio
        articleFreemarkerService.buildArticleToMinIO(apArticle, dto.getContent());

        //3.结果返回
        return ResponseResult.okResult(apArticle.getId());
    }

    @Autowired
    private CacheService cacheService;

    /**
     * 加载用户行为数据--数据回显
     *
     * @param dto
     * @return
     */
    public ResponseResult loadArticleBehavior(ArticleInfoDto dto) {
        //1.检查参数
        if (dto == null || dto.getArticleId() == null || dto.getAuthorId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //设置初始数据
        boolean isfollow = false, islike = false, isunlike = false, iscollection = false;
        ApUser user = AppThreadLocalUtil.getUser();

        if (user != null) {
            //喜欢行为
            String likeBehaviorJson = (String) cacheService.hGet(BehaviorConstants.LIKE_BEHAVIOR + dto.getArticleId().toString(), user.getId().toString());
            if (StringUtils.isNotBlank(likeBehaviorJson)) {
                islike = true;
            }
            //不喜欢行为
            String unlikeBehaviorJson = (String) cacheService.hGet(BehaviorConstants.UN_LIKE_BEHAVIOR + dto.getArticleId().toString(), user.getId().toString());
            if (StringUtils.isNotBlank(unlikeBehaviorJson)) {
                isunlike = true;
            }
            //是否收藏
            String collectionJson = (String) cacheService.hGet(BehaviorConstants.COLLECTION_BEHAVIOR + user.getId(), dto.getArticleId().toString());
            if (StringUtils.isNotBlank(collectionJson)) {
                iscollection = true;
            }
            //是否关注
            Double score = cacheService.zScore(BehaviorConstants.APUSER_FOLLOW_RELATION + user.getId(), dto.getAuthorId().toString());
            if (score != null) {
                isfollow = true;
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("islike", islike);
        map.put("isunlike", isunlike);
        map.put("iscollection", iscollection);
        map.put("isfollow", isfollow);

        return ResponseResult.okResult(map);
    }

    /**
     * 更新文章分值
     * 更新缓存中的文章热点数据
     *
     * @param mess
     * @return
     */
    public void updateScore(ArticleVisitStreamMess mess) {
        //1.更新文章的阅读，点赞，评论，收藏的数量
        ApArticle apArticle = UpdateArticle(mess);
        //2.计算文章分值
        Integer score = coumputeScore(apArticle);
        score = score * 3;
        //3.替换当前文章对应频道热点数据
        replaceDateToRedis(HOT_ARTICLE_FIRST_PAGE + apArticle.getChannelId(), apArticle, score);
        //4.替换推荐对应的热点数据
        replaceDateToRedis(HOT_ARTICLE_FIRST_PAGE + DEFAULT_TAG, apArticle, score);
    }

    /**
     * 查询相应的文章信息
     *
     * @param dto
     * @return
     */
    @Override
    public PageResponseResult findNewsComments(ArticleCommentDto dto) {
        //检查分页参数
        dto.checkParam();
        IPage page = new Page(dto.getPage(), dto.getSize());
        //根据id查询相应的文章信息
        LambdaQueryWrapper<ApArticle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApArticle::getAuthorId, dto.getWmUserId());
        if (dto.getBeginDate()!=null&&dto.getEndDate()!=null){
            queryWrapper.ge(ApArticle::getPublishTime,dto.getBeginDate()).le(ApArticle::getPublishTime,dto.getEndDate());
        }
        page = page(page, queryWrapper);
        List<ApArticle> list = list(queryWrapper);
        List<ArticleCommnetVo> resultList=new ArrayList<>();
        for (ApArticle apArticle : list) {
            ArticleCommnetVo vo=new ArticleCommnetVo();
            ApArticleConfig apArticleConfig = apArticleConfigMapper.selectOne((Wrappers.<ApArticleConfig>lambdaQuery().eq(ApArticleConfig::getArticleId, apArticle.getId())));
            BeanUtils.copyProperties(apArticle,vo);
            vo.setIsComment(apArticleConfig.getIsComment());
            vo.setComments(apArticle.getComment());
            resultList.add(vo);
        }

        //分页查询
        int start = (int)((page.getCurrent() - 1) * page.getSize());
        int end = (int)((start + page.getSize()) > resultList.size() ? resultList.size() : (page.getSize() * page.getCurrent()));
        page.setTotal(resultList.size());
        if (page.getSize()*(page.getCurrent()-1) <= page.getTotal()) {
            // 分隔列表 当前页存在数据时 设置
            page.setRecords(resultList.subList(start, end));
        }

        //4.返回结果
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;
    }

    /**
     * 打开或关闭评论
     * @param dto
     * @return
     */
    public ResponseResult updateCommentStatus(CommentConfigDto dto){
        //1.打开评论
        if (dto.getOperation()==1){
            getCommentConfig(dto, true);
        }else { //关闭评论
            getCommentConfig(dto, false);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 更改评论先关配置
     * @param dto
     * @param isComment
     */
    private void getCommentConfig(CommentConfigDto dto, boolean isComment) {
        LambdaQueryWrapper<ApArticleConfig> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ApArticleConfig::getArticleId, dto.getArticleId());
        ApArticleConfig apArticleConfig = apArticleConfigMapper.selectOne(lambdaQueryWrapper);
        apArticleConfig.setIsComment(isComment);
        apArticleConfigMapper.updateById(apArticleConfig);
    }

    /**
     * 查询喜欢和收藏数
     * @param apUserId
     * @param beginDate
     * @param endDate
     * @return
     */
    public ResponseResult queryLikesAndConllections(Integer apUserId, Date beginDate,Date endDate){
        LambdaQueryWrapper<ApArticle> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(ApArticle::getAuthorId,apUserId);
        queryWrapper.ge(ApArticle::getPublishTime,beginDate).le(ApArticle::getPublishTime,endDate);
        List<ApArticle> list = list(queryWrapper);
        Map<String,Integer> resultMap=new HashMap<>();
        Integer likes= 0;
        Integer collection= 0;
        for (ApArticle apArticle : list) {
            if (apArticle.getLikes()!=null){
                likes=likes + apArticle.getLikes();
            }
            if (apArticle.getCollection()!=null){
                collection = collection + apArticle.getCollection();
            }
        }
        resultMap.put("likes",likes);
        resultMap.put("collections",collection);
        return ResponseResult.okResult(resultMap);
    }

    /**
     * 图文分页查询
     * @param dto
     * @return
     */
    public PageResponseResult newPage(StatisticsDto dto){
        //类型转换
        Date beginDate = DateUtils.stringToDate(dto.getBeginDate());
        Date endDate = DateUtils.stringToDate(dto.getEndDate());
        //分页查询
        IPage page = new Page(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<ApArticle> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(ApArticle::getAuthorId,dto.getApUserId())
                .between(ApArticle::getPublishTime,beginDate,endDate)
                .select(ApArticle::getId,ApArticle::getTitle,ApArticle::getLikes,ApArticle::getCollection,ApArticle::getComment,ApArticle::getViews)
                .orderByDesc(ApArticle::getPublishTime);
        page=page(page,queryWrapper);
        PageResponseResult responseResult=new PageResponseResult(dto.getPage(),dto.getSize(), (int) page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;
    }


    /**
     * 替换数据并存入到redis
     *
     * @param HOT_ARTICLE_FIRST_PAGE
     * @param apArticle
     * @param score
     */
    private void replaceDateToRedis(String HOT_ARTICLE_FIRST_PAGE, ApArticle apArticle, Integer score) {
        String articleListStr = cacheService.get(HOT_ARTICLE_FIRST_PAGE);
        if (StringUtils.isNotBlank(articleListStr)) {
            List<HotArticleVo> hotArticleVoList = JSON.parseArray(articleListStr, HotArticleVo.class);
            Boolean flag = true;
            //如果缓存中只存在该文章，只更新分值
            for (HotArticleVo hotArticleVo : hotArticleVoList) {
                if (hotArticleVo.getId().equals(apArticle.getId())) {
                    hotArticleVo.setScore(score);
                    flag = false;
                    break;
                }
            }
            //如果缓存中不存在，查询缓存中分值最小的一条数据，进行分值比较，如果当前文章分值大于缓存中的数据，就替换
            if (flag) {
                if (hotArticleVoList.size() >= 30) {    //排序
                    hotArticleVoList = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
                    HotArticleVo lastHot = hotArticleVoList.get(hotArticleVoList.size() - 1);
                    if (score >= lastHot.getScore()) {
                        hotArticleVoList.remove(lastHot);
                        HotArticleVo hot = new HotArticleVo();
                        BeanUtils.copyProperties(apArticle, hot);
                        hot.setScore(score);
                        hotArticleVoList.add(hot);
                    }
                } else {
                    //新增
                    HotArticleVo hot = new HotArticleVo();
                    BeanUtils.copyProperties(apArticle, hot);
                    hot.setScore(score);
                    hotArticleVoList.add(hot);
                }
            }
            //排序后缓存到redis
            hotArticleVoList = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
            cacheService.set(HOT_ARTICLE_FIRST_PAGE, JSON.toJSONString(hotArticleVoList));
        }
    }

    /**
     * 更新文章行为数量
     *
     * @param mess
     */
    private ApArticle UpdateArticle(ArticleVisitStreamMess mess) {
        ApArticle apArticle = getById(mess.getArticleId());
        apArticle.setCollection(apArticle.getCollection() == null ? 0 : apArticle.getCollection() + mess.getCollect());
        apArticle.setComment(apArticle.getComment() == null ? 0 : apArticle.getComment() + mess.getComment());
        apArticle.setLikes(apArticle.getLikes() == null ? 0 : apArticle.getLikes() + mess.getLike());
        apArticle.setViews(apArticle.getViews() == null ? 0 : apArticle.getViews() + mess.getView());
        updateById(apArticle);
        return apArticle;
    }

    /**
     * 计算文章具体的分值
     *
     * @param apArticle
     * @return
     */
    private Integer coumputeScore(ApArticle apArticle) {
        Integer score = 0;
        if (apArticle.getLikes() != null) {    //点赞 权重 3
            score += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        if (apArticle.getViews() != null) {    //阅读 权重 1
            score += apArticle.getViews();
        }
        if (apArticle.getCollection() != null) {    //收藏 权重 8
            score += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }
        if (apArticle.getComment() != null) {    //评论 权重 5
            score += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        return score;
    }

    /**
     * 根据参数加载文章列表
     *
     * @param type      1为加载更多  2为加载最新
     * @param dto
     * @param firstPage true--首页   false--非首页
     * @return
     */
    public ResponseResult load2(Short type, ArticleHomeDto dto, boolean firstPage) {
        if (firstPage) {
            String json = cacheService.get(HOT_ARTICLE_FIRST_PAGE + dto.getTag());
            if (StringUtils.isNotBlank(json)) {
                List<HotArticleVo> hotArticleVoList = JSON.parseArray(json, HotArticleVo.class);
                ResponseResult responseResult = ResponseResult.okResult(hotArticleVoList);
                return responseResult;
            }
        }
        return load(type, dto);
    }

}